package com.fyh.hiring.talent.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.fyh.hiring.talent.dao.ResumeDao;
import com.fyh.hiring.talent.dao.TalentDao;
import com.fyh.hiring.talent.entity.ResumeEntity;
import com.fyh.hiring.talent.entity.TalentEntity;

public class TalentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TalentDao talentDao = new TalentDao();
private ResumeDao resumeDao = new ResumeDao();
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 1.获取参数
		String command = request.getParameter("command");

		if ("login".equals(command)) {
			// 调用登录的方法
			try {
				login(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else if ("register".equals(command)) {
			// 调用注册方法
			try {
				register(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if("logout".equals(command)){
			  //调用注销的方法
			try {
				logout(request,response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("update".equals(command)){
			//调用修改个人资料的方法
			update(request,response);
		}else if("main".equals(command)){
			//调用修改个人资料的方法
			main(request,response);
		}else{
			throw new RuntimeException("请求失败");
		}
		
		

		// 2.调用业务逻辑
		// 3.转向
	}


	

	/**
	 * 登录的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		// 1.获取参数
		String code = request.getParameter("code");
		String password = request.getParameter("password");

		// 2.调用业务逻辑
		TalentEntity talent = talentDao.login(code, password);

		// 3.转向
		if (talent == null) {
			// 如果等于空，那就说明没有这个数据，那就重新返回登录页面
			response.sendRedirect("view/talent/login.jsp?errorMsg=true");

		} else {
			//成功
			request.getSession().setAttribute("talent", talent);
             //告诉浏览器从上一步重新发一个地址到Servlet，然后Servlet得到一个command参数
			// response.sendRedirect("TalentServlet?command=main");
			 
			response.sendRedirect("TalentServlet?command=main&talentId="+talent.getId());
			System.out.println("1");
		}
	}
	
	/**
	 *专门负责转到求职者的主页，同时携带简历的集合,解决了注销回退的问题:挡在main页面刷新一次时，就是让页面重新加载，也就是在
	 *执行一次main方法
	 */
	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 //登录成功，查询登陆者所有的简历
	     // TalentEntity talent =(TalentEntity) request.getSession().getAttribute("talent");
		//int talentId =Integer.parseInt(request.getParameter("talentId"));
		
	       Object obj = request.getSession().getAttribute("talent");
	       if ( obj == null) {
	    	   response.sendRedirect("view/talent/login.jsp?logoutSuccess=true");
	   	}else{
	   		int talentId =((TalentEntity)obj).getId();
         List<ResumeEntity> listAllResume = resumeDao.listResume(talentId);
                request.setAttribute("listAllResume", listAllResume);
	      	    request.getRequestDispatcher("view/talent/main.jsp").forward(
				request, response);
		}
     
	       //刷新时只是调用了main方法，这个参数是无法获取的！
//	       int talentId =Integer.parseInt(request.getParameter("talentId"));
//	       List<ResumeEntity> listAllResume = resumeDao.listResume(talentId);
//            request.setAttribute("listAllResume", listAllResume);
//            System.out.println(".....");
//     	    request.getRequestDispatcher("view/talent/main.jsp").forward(
//			request, response);
	}
	
	
	/**
	 * 这是修改个人资料的方法
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
          //1.获取参数
	     TalentEntity talentEntity = (TalentEntity) request.getSession().getAttribute("talent");
	     
		String passWord = request.getParameter("password");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		int age = Integer.parseInt(request.getParameter("age"));
		//int gender = Integer.parseInt(request.getParameter("gender"));
		String[] hobbies = request.getParameterValues("hobby");
		
		// 由于参数过多，所以放到封装实体类里面
		TalentEntity talent = new TalentEntity();
		
	    talent.setId(talentEntity.getId());
		talent.setPassWord(passWord);
		talent.setName(name);
		talent.setEmail(email);
		talent.setPhone(phone);
		talent.setAge(age);
		//talent.setGender(gender);
		if (hobbies != null) {
			talent.setHobby(StringUtils.join(hobbies, "|"));
		}else{
			talent.setHobby(""); //什么也不选也要去更新哈，不然session用的是原来的只
		}
		  // 2.调用业务逻辑
		 int row =talentDao.update(talent);
		  // 3.转向
		 if (row ==1) {
			 //修改成功
			 //更新session！这是重点，如果不更新，那么这一切就白做了
			 talent.setCode(talentEntity.getCode()); //登录的时候有code，所以我这里要加上
			 request.getSession().setAttribute("talent", talent);  //这是更新后的session
			 
			 response.sendRedirect("view/talent/talent-info.jsp?updateSuccess=true");
		}else{
			//修改失败
			response.sendRedirect("view/talent/talent-info.jsp?updateError=true");
		}
	}


	/**
	 * 注册的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	private void register(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException {
		// 1.获取参数
		String code = request.getParameter("code");
		String passWord = request.getParameter("password");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		int age = Integer.parseInt(request.getParameter("age"));
		int gender = Integer.parseInt(request.getParameter("gender"));
		String[] hobbies = request.getParameterValues("hobby");

		// 由于参数过多，所以放到封装实体类里面
		TalentEntity talent = new TalentEntity();
		talent.setCode(code);
		talent.setPassWord(passWord);
		talent.setName(name);
		talent.setEmail(email);
		talent.setPhone(phone);
		talent.setAge(age);
		talent.setGender(gender);
		if (hobbies != null) {
			// StringBuilder sb= new StringBuilder();
			// for (int i = 0; i < hobbies.length; i++) {
			// if ( i ==hobbies.length-1) {
			// sb.append(hobbies[i]);
			// }else{
			// sb.append(hobbies[i]+"|");
			// }
			// }
			// talent.setHobby(sb.toString());
			// 这个和上面一样，这是apache提供的工具类
			talent.setHobby(StringUtils.join(hobbies, "|"));
		}
		// 2.调用业务逻辑
		int row = talentDao.register(talent);

		// 3.转向
		if (row == 1) {
			// 如果等于1，说明1行受影响，就是注册成功，那么回到登录页面
			response.sendRedirect("view/talent/login.jsp?registerSuccess=true");

		} else {
			// 如果失败则回到注册页面
			// response.sendRedirect("view/talent/register.jsp?registerError=true");

			request.setAttribute("talent", talent);
			request.getRequestDispatcher(
					"view/talent/register.jsp?registerError=true").forward(
					request, response);
		}
	}
	
	/**
	 * 注销
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException {
		        //让session失效
		       request.getSession().invalidate();
		       //然后跳转
		       response.sendRedirect("view/talent/login.jsp?logoutSuccess=true");
	}


}
